var path = require("path");
var fs = require("fs");
var express = require('express');
var cheerio = require('cheerio');
//var dataCache = require("./platform/platform-datacache");

var config,server,logger;
//dataCache.set("applist",[]);

module.exports = function(opts){
    config = opts.config;
    server = opts.server;
    logger = opts.logger;

    return {
        load:load_app
    }
}

/*
  绑定主页
*/
function appmw_homepage(app_config){
    var tpl_dir = path.resolve(config.root_dir,app_config.app_root,app_config.app_name,"index.html");

    server.get("/"+app_config.app_name+'/:app_id',function(req,res){
        var app_id = req.params["app_id"];
        var page_content = fs.readFileSync(tpl_dir);
        const $ = cheerio.load(page_content,{
            decodeEntities: false
        });
        $("title").html(app_config.name);
        $("meta[name='description']").attr("content",app_config.description);

        $("head").append("<script>var global_app_name='"+app_config.app_name+"';var global_app_id='"+app_id+"';</script>");

        res.header("Content-Type","text/html");
        res.end($.html());
        
    });

    server.get("/"+app_config.app_name,function(req,res){
        res.redirect("/"+app_config.app_name+'/dev-test');
    });
}

/*
  设置静态文件目录
*/
function appmw_dev_static(app_config){
    var url_path = "/"+app_config.app_name;
    console.log(config.root_dir,app_config.app_root,url_path);
    server.use(url_path,express.static(path.join(config.root_dir,app_config.app_root,url_path)));
}



/*
  load app
*/
function load_app(app_name,root_dir){
    logger.info("loading app "+app_name);

    var app_config = require(path.join(root_dir, config.app_root,app_name,"config.json"));
    app_config.app_name = app_name;
    app_config.app_root = config.app_root;

    app_config.app_id = app_config.app_name + "-dev";
    appmw_homepage(app_config);
    appmw_dev_static(app_config);
    //dataCache.get("applist").push(app_config);
}